package cn.innosmart.aq.manager;

import com.tutk.p2p.ConnectionEntity;
import com.tutk.p2p.ResponseHandler;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;

import cn.innosmart.aq.bean.AquariumBean;
import cn.innosmart.aq.util.SystemConstant;

/**
 * Created by David on 2015/6/30.
 */
public class PlaceManager extends BaseManager {
    private static AddCallBack addCallBack;
    private static RemoveCallBack removeCallBack;
    private static UpdateCallBack updateCallBack;
    private static ChangeMaintainModeCallback changeMaintainModeCallback;

    private String Tag = "PlaceManager";
    /**
     * {"code":0,"message":"Success","result":{"id":"SN0121_gYFz93hoAC9JbA1BnIHJ"},"type":"resp","callid":1437702271391,"method":"PlaceManager.Add"}
     */
    /**
     * 添加鱼缸回调函数
     */
    private ResponseHandler.ResponseCallback mPlaceManagerAddCallBack = new ResponseHandler.ResponseCallback() {
        @Override
        public void onResponseCallback(ConnectionEntity connectionEntity, String message) {
            log(Tag, "PlaceManager.Add get response=" + message);
            String id = null;
            try {
                JSONObject jsonObject = new JSONObject(message);
                id = jsonObject.getJSONObject("result").getString("id");
            } catch (JSONException e) {
                e.printStackTrace();
            }
            if (addCallBack != null) {
                addCallBack.onAddResponseCallBack(0, id);
            }
            connectionEntity.flags.remove(connectionEntity.PLACEADD);
            if (connectionEntity.iConnectionEntity != null) {
                connectionEntity.iConnectionEntity.onBoxMessageOver(0, connectionEntity.PLACEADD, id);
            }
        }
    };
    /**
     * 删除鱼缸回调函数
     * {"code":0,"message":"Success","type":"resp","callid":1437723642586,"method":"PlaceManager.Remove"}
     */
    private ResponseHandler.ResponseCallback mPlaceManagerRemoveCallBack = new ResponseHandler.ResponseCallback() {
        @Override
        public void onResponseCallback(ConnectionEntity connectionEntity, String message) {
            log(Tag, "PlaceManager.Remove get response=" + message);
            connectionEntity.flags.remove(connectionEntity.PLACEREMOVE);
            JSONObject jRoot = null;
            try {
                jRoot = new JSONObject(message);
                int rspCode = jRoot.getInt("code");
                String rspMsg = jRoot.getString("message");
                if (0 == rspCode && "Success".equals(rspMsg)) {
                    if (removeCallBack != null) {
                        removeCallBack.onRemoveResponseCallBack(0);
                    }
                } else {
                    log(Tag, "PlaceManager.REMOVE fail: " + rspMsg);
                }
            } catch (Exception e) {

            }
            if (connectionEntity.iConnectionEntity != null) {
                connectionEntity.iConnectionEntity.onBoxMessageOver(0, connectionEntity.PLACEREMOVE, null);
            }
        }
    };
    /**
     * {"code":0,"message":"Success","result":
     * {
     * "places": [
     * {
     * "id": "SN0121_gYFz93hoAC9JbA1BnIHJ",
     * "title": "AQ1",
     * "order": 1,
     * "icon_type": "icon_type_2",
     * "icon_data": "icon_data_2",
     * "addresses": ["zwave:\/\/e5ad378b\/45\/49\/1\/1","zwave:\/\/e5ad378b\/45\/49\/1\/1","zwave:\/\/e5ad378b\/45\/49\/1\/1"]
     * },
     * {
     * "id": "SN0121_TC89hc8LMdLOIJb9hHGw",
     * "title": "AQ1",
     * "order": 1,
     * "icon_type": "icon_type_2",
     * "icon_data": "icon_data_2",
     * "addresses": []
     * }
     * ]
     * },"type":"resp",
     * "callid":1437704596523,"method":"PlaceManager.List"}
     */

    /**
     * List鱼缸列表函数
     */
    private ResponseHandler.ResponseCallback mPlaceManagerListCallBack = new ResponseHandler.ResponseCallback() {
        @Override
        public void onResponseCallback(ConnectionEntity connectionEntity, String message) {
            log(Tag, "PlaceManager.List get response=" + message);
            connectionEntity.flags.remove(connectionEntity.PLACELIST);
            SystemConstant.aquariumList = new ArrayList<AquariumBean>();
            //此处要改为处理多连接
            JSONObject jRoot = null;
            try {
                jRoot = new JSONObject(message);
                int rspCode = jRoot.getInt("code");
                String rspMsg = jRoot.getString("message");
                if (0 == rspCode && "Success".equals(rspMsg)) {
                    JSONArray jsonArray = jRoot.getJSONObject("result").getJSONArray("places");
                    AquariumBean aquariumBean;
                    for (int i = 0; i < jsonArray.length(); i++) {
                        aquariumBean = new AquariumBean(jsonArray.getJSONObject(i));
                        SystemConstant.aquariumList.add(aquariumBean);
                    }
                    //排序
//                        Collections.sort(SystemConstant.aquariumList, new Comparator<AquariumBean>() {
//                            @Override
//                            public int compare(AquariumBean lhs, AquariumBean rhs) {
//                                return lhs.getOrder() - rhs.getOrder();
//                            }
//                        });
                } else {
                    log(Tag, "PlaceManager.List fail: " + rspMsg);
                }
            } catch (Exception e) {

            }
            if (connectionEntity.iConnectionEntity != null) {
                connectionEntity.iConnectionEntity.onBoxMessageOver(0, connectionEntity.PLACELIST, null);
            }
        }
    };
    //{"code":0,"message":"Success","type":"resp","callid":1441934343961,"method":"PlaceManager.Update"}
    /**
     * 更新鱼缸信息回调函数
     */
    private ResponseHandler.ResponseCallback mPlaceManagerUpdateCallBack = new ResponseHandler.ResponseCallback() {
        @Override
        public void onResponseCallback(ConnectionEntity connectionEntity, String message) {
            log(Tag, "PlaceManager.Update get response=" + message);
            JSONObject jRoot = null;
            try {
                jRoot = new JSONObject(message);
                int rspCode = jRoot.getInt("code");
                String rspMsg = jRoot.getString("message");
                if (0 == rspCode && "Success".equals(rspMsg)) {
                    //成功
                    if (updateCallBack != null) {
                        updateCallBack.onUpdateResponseCallBack(0);
                    }
                } else {
                    //失败
                    if (updateCallBack != null) {
                        updateCallBack.onUpdateResponseCallBack(-1);
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
                //失败
                if (updateCallBack != null) {
                    updateCallBack.onUpdateResponseCallBack(-2);
                }
            }
        }
    };

    private ResponseHandler.ResponseCallback mPlaceManagerChangeMaintainModeCallBack = new ResponseHandler.ResponseCallback() {
        @Override
        public void onResponseCallback(ConnectionEntity connectionEntity, String message) {
            log(Tag, "PlaceManager.ChangeMaintain get response=" + message);
            JSONObject jRoot = null;
            try {
                jRoot = new JSONObject(message);
                int rspCode = jRoot.getInt("code");
                String rspMsg = jRoot.getString("message");
                if (0 == rspCode && "Success".equals(rspMsg)) {
                    //成功
                    if (changeMaintainModeCallback != null) {
                        changeMaintainModeCallback.onChangeMaintainModeCallback(0);
                    }
                } else {
                    //失败
                    if (changeMaintainModeCallback != null) {
                        changeMaintainModeCallback.onChangeMaintainModeCallback(-1);
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
                //失败
                if (changeMaintainModeCallback != null) {
                    changeMaintainModeCallback.onChangeMaintainModeCallback(-2);
                }
            }
        }
    };

    private PlaceManager() {
    }

    public static PlaceManager getInstance() {
        return PlaceManagerInstance.instance;
    }

    // PlaceManager.Add

    public boolean Add(ConnectionEntity connectionEntity, String params) {
        log(Tag, "Add. UID = " + connectionEntity.getUid() + ", params = " + params);
        connectionEntity.flags.add(connectionEntity.PLACEADD);
        long callid = System.currentTimeMillis();
        ResponseHandler handler = new ResponseHandler();
        handler.setCallback(mPlaceManagerAddCallBack);
        connectionEntity.mReqRspHashMap.put(callid, handler);
        if (!SendCommand(connectionEntity, connectionEntity.getUid(), "PlaceManager.Add", params, callid)) {
            connectionEntity.mReqRspHashMap.remove(callid);
            return false;
        } else {
            return true;
        }
    }

    /**
     * 带回调函数的添加鱼缸方法
     * @param connectionEntity
     * @param params
     * @param addCallBack
     * @return
     */
    public boolean Add(ConnectionEntity connectionEntity, String params, AddCallBack addCallBack) {
        log(Tag, "Add. UID = " + connectionEntity.getUid() + ", params = " + params);
        this.addCallBack = addCallBack;
        connectionEntity.flags.add(connectionEntity.PLACEADD);
        long callid = System.currentTimeMillis();
        ResponseHandler handler = new ResponseHandler();
        handler.setCallback(mPlaceManagerAddCallBack);
        connectionEntity.mReqRspHashMap.put(callid, handler);
        if (!SendCommand(connectionEntity, connectionEntity.getUid(), "PlaceManager.Add", params, callid)) {
            connectionEntity.mReqRspHashMap.remove(callid);
            return false;
        } else {
            return true;
        }
    }

    // PlaceManager.Remove

    /**
     * 删除鱼缸
     * @param connectionEntity
     * @param params
     * @return
     */
    public boolean Remove(ConnectionEntity connectionEntity, String params) {
        log(Tag, "Remove. UID = " + connectionEntity.getUid() + ", params = " + params);
        connectionEntity.flags.add(connectionEntity.PLACEREMOVE);
        long callid = System.currentTimeMillis();
        ResponseHandler handler = new ResponseHandler();
        handler.setCallback(mPlaceManagerRemoveCallBack);
        connectionEntity.mReqRspHashMap.put(callid, handler);
        if (!SendCommand(connectionEntity, connectionEntity.getUid(), "PlaceManager.Remove", params, callid)) {
            connectionEntity.mReqRspHashMap.remove(callid);
            return false;
        } else {
            return true;
        }
    }

    /**
     * 带回掉函数的删除鱼缸方法
     * @param connectionEntity
     * @param params
     * @param removeCallBack
     * @return
     */
    public boolean Remove(ConnectionEntity connectionEntity, String params, RemoveCallBack removeCallBack) {
        log(Tag, "Remove. UID = " + connectionEntity.getUid() + ", params = " + params);
        connectionEntity.flags.add(connectionEntity.PLACEREMOVE);
        this.removeCallBack = removeCallBack;
        long callid = System.currentTimeMillis();
        ResponseHandler handler = new ResponseHandler();
        handler.setCallback(mPlaceManagerRemoveCallBack);
        connectionEntity.mReqRspHashMap.put(callid, handler);
        if (!SendCommand(connectionEntity, connectionEntity.getUid(), "PlaceManager.Remove", params, callid)) {
            connectionEntity.mReqRspHashMap.remove(callid);
            return false;
        } else {
            return true;
        }
    }

    // PlaceManager.List
    public boolean List(ConnectionEntity connectionEntity) {
        log(Tag, "List. UID = " + connectionEntity.getUid());
        connectionEntity.flags.add(connectionEntity.PLACELIST);
        long callid = System.currentTimeMillis() / 1000;
        JSONObject jParams = new JSONObject();
        ResponseHandler handler = new ResponseHandler();
        handler.setCallback(mPlaceManagerListCallBack);
        connectionEntity.mReqRspHashMap.put(callid, handler);
        if (!SendCommand(connectionEntity, connectionEntity.getUid(), "PlaceManager.List", jParams.toString(), callid)) {
            connectionEntity.mReqRspHashMap.remove(callid);
            return false;
        } else {
            return true;
        }
    }

    // PlaceManager.List
    public boolean List(ConnectionEntity connectionEntity, int delay) {
        log(Tag, "List. UID = " + connectionEntity.getUid());
        connectionEntity.flags.add(connectionEntity.PLACELIST);
        long callid = System.currentTimeMillis() / 1000;
        if (delay != 0) {
            callid = callid + delay;
        }
        JSONObject jParams = new JSONObject();
        ResponseHandler handler = new ResponseHandler();
        handler.setCallback(mPlaceManagerListCallBack);
        connectionEntity.mReqRspHashMap.put(callid, handler);
        if (!SendCommand(connectionEntity, connectionEntity.getUid(), "PlaceManager.List", jParams.toString(), callid)) {
            connectionEntity.mReqRspHashMap.remove(callid);
            return false;
        } else {
            return true;
        }
    }

    // PlaceManager.Update
    public boolean Update(ConnectionEntity connectionEntity, String params, UpdateCallBack updateCallBack) {
        log(Tag, "UPdate. UID = " + connectionEntity.getUid() + ", params = " + params);
        this.updateCallBack = updateCallBack;
        long callid = System.currentTimeMillis();
        ResponseHandler handler = new ResponseHandler();
        handler.setCallback(mPlaceManagerUpdateCallBack);
        connectionEntity.mReqRspHashMap.put(callid, handler);
        if (!SendCommand(connectionEntity, connectionEntity.getUid(), "PlaceManager.Update", params, callid)) {
            connectionEntity.mReqRspHashMap.remove(callid);
            return false;
        } else {
            return true;
        }
    }

    public boolean ChangeMaintainMode(ConnectionEntity connectionEntity, String params, ChangeMaintainModeCallback ChangeMaintainModeCallback) {

        log(Tag, "ChangeMaintainMode. UID = " + connectionEntity.getUid() + ", params = " + params);
        this.changeMaintainModeCallback = ChangeMaintainModeCallback;
        long callid = System.currentTimeMillis();
        ResponseHandler handler = new ResponseHandler();
        handler.setCallback(mPlaceManagerChangeMaintainModeCallBack);
        connectionEntity.mReqRspHashMap.put(callid, handler);
        if (!SendCommand(connectionEntity, connectionEntity.getUid(), "PlaceManager.ChangeMaintain", params, callid)) {
            connectionEntity.mReqRspHashMap.remove(callid);
            return false;
        } else {
            return true;
        }

    }

    public interface AddCallBack {
        void onAddResponseCallBack(int ret, String uid);
    }

    public interface RemoveCallBack {
        void onRemoveResponseCallBack(int ret);
    }

    public interface UpdateCallBack {
        void onUpdateResponseCallBack(int ret);
    }

    public interface ChangeMaintainModeCallback {
        void onChangeMaintainModeCallback(int ret);
    }

    private static class PlaceManagerInstance {
        private static final PlaceManager instance = new PlaceManager();
    }
}
